package czhdao

import (
	"Cgo/front/models"
	"Cgo/global"
	"errors"
)

type loginDao struct{}

var LoginDao = loginDao{}

// 用户登录
func (l loginDao) UserLogin(account string, password string) (models.CzhUser, error) {
	var userInfo models.CzhUser
	if r := global.DB.Raw("SELECT * FROM czh_user WHERE account = ? AND password = ?", account, password).Scan(&userInfo); r.RowsAffected > 0 {
		return userInfo, nil
	} else {
		return userInfo, errors.New("没有查到数据")
	}
}

// 用户注册
func (l loginDao) UserRegistration(account string, password string, name string, avatar string, gender string, surplus string) error {
	if r := global.DB.Exec("INSERT INTO czh_user (account, password, name, avatar, gender, surplus) VALUES (?, ?, ?, ?, ?, ?)", account, password, name, avatar, gender, surplus); r.Error != nil {
		return r.Error
	} else {
		return nil
	}
}

// 获取用户信息
func (l loginDao) GetUserInfo(id string) (models.CzhUser, error) {
	var userInfo models.CzhUser
	if r := global.DB.Raw("SELECT * FROM czh_user WHERE id = ?", id).Scan(&userInfo); r.RowsAffected > 0 {
		return userInfo, nil
	} else {
		return userInfo, errors.New("没有查到数据")
	}
}

// 获取所有用户信息;
func (l loginDao) GetAllUserInfo() ([]models.CzhUser, error) {
	var allUserInfo []models.CzhUser
	if r := global.DB.Raw("SELECT * FROM czh_user").Scan(&allUserInfo); r.RowsAffected > 0 {
		return allUserInfo, nil
	} else {
		return allUserInfo, errors.New("没有查到数据")
	}
}

// 编辑用户信息
func (l loginDao) UserEdit(id int, avatar string, name string, gender string, synopsis string, surplus string) error {
	if r := global.DB.Exec("UPDATE czh_user SET name = ?, avatar = ?, gender = ?, synopsis = ?, surplus = ? WHERE id = ?", name, avatar, gender, synopsis, surplus, id); r.Error != nil {
		return r.Error
	} else {
		return nil
	}
}

// 用户删除
func (l loginDao) UserRemove(id int) error {
	if r := global.DB.Exec("DELETE FROM czh_user WHERE id = ?", id); r.Error != nil {
		return r.Error
	} else {
		return nil
	}
}
